package com.xuantian.baoming.controller;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuantian.baoming.BaomingApplication;
import com.xuantian.baoming.entity.OrderInfo;
import com.xuantian.baoming.entity.WorksInfo;
import com.xuantian.baoming.enums.OrderStatus;
import com.xuantian.baoming.service.OrderInfoService;
import com.xuantian.baoming.vo.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@CrossOrigin //开放前端的跨域访问
@RestController
@RequestMapping("/api/order-info")
@Slf4j
public class OrderInfoController {

    @Resource
    private OrderInfoService orderInfoService;

    //报名成功人员导出
    @GetMapping("/excelExprot")
    @SneakyThrows
    private void excelExprot(HttpServletResponse response){

        //查询报名成功人员信息
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getStatus,OrderStatus.SUCCESS.getType());
        List<OrderInfo> list = orderInfoService.list(wrapper);

        String fileName0 = URLEncoder.encode("报名人员信息表" , "UTF-8");
//        UUID uuid = UUID.randomUUID();
        String fileName =fileName0 + System.currentTimeMillis();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename= " + fileName + ".xlsx");

        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream excelTemplate = BaomingApplication.class.getClassLoader().getResourceAsStream("报名人员信息.xlsx")
        ) {

            // 使用 EasyExcel 写入
            EasyExcel.write(outputStream)
                    .withTemplate(excelTemplate)
                    .sheet()
                    .doFill(list);

            // 刷新输出流
            outputStream.flush();

        } catch (IOException e) {
            // 记录异常日志，并在必要时返回错误响应
            log.error("Error generating Excel file: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        log.info("========》 excel导出成功,文件名称: {}", fileName);

    }

    /**
     * 分页查询完成支付的用户，模糊查询
     * @param page
     * @param size
     * @param name
     * @param contact
     * @return
     */
    @GetMapping("/list")
    public R<List<Page<OrderInfo>>> list(@RequestParam(required = false) Integer page,
                                         @RequestParam(required = false) Integer size,
                                         @RequestParam(required = false) String name,
                                         @RequestParam(required = false) String contact,
                                         @RequestParam(required = false) String grade){
        if (page == null || size == null){
            page = 1;
            size = 10;
        }
        Page<OrderInfo> page1 = new Page<>(page, size);
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getStatus,OrderStatus.SUCCESS.getType());
        wrapper.like(!StringUtils.isEmpty(name),OrderInfo::getName,name);
        wrapper.like(!StringUtils.isEmpty(contact),OrderInfo::getContact,contact);
        wrapper.like(!StringUtils.isEmpty(grade), OrderInfo::getGrade, grade);
        Page<OrderInfo> orderInfoPage = orderInfoService.page(page1, wrapper);
        return R.ok(orderInfoPage);
    }

    /**
     * 查询本地订单状态
     * @param orderNo
     * @return
     */
    @GetMapping("/query-order-status/{orderNo}")
    public R queryOrderStatus(@PathVariable String orderNo){

        String orderStatus = orderInfoService.getOrderStatus(orderNo);
        if (orderStatus == null){
            return R.fail("订单不存在");
        }
        if(OrderStatus.SUCCESS.getType().equals(orderStatus)){
            return R.ok("支付成功"); //支付成功
        }
        return R.fail(101,orderStatus);
    }
}
